package cn.caixiong.basic.service.Impl;

import cn.caixiong.basic.domain.BaseDomain;
import cn.caixiong.basic.query.BaseQuery;
import cn.caixiong.basic.service.IBaseService;
import cn.caixiong.basic.util.PageList;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;
@Transactional(readOnly = true,propagation= Propagation.SUPPORTS) //事务管理
public class BaseServiceImpl<T extends BaseDomain,Q extends BaseQuery> implements IBaseService<T, Q> {
    @Autowired
    Mapper<T> basemapper;
    @Override
    public T findOne(Long id) {
        return basemapper.selectByPrimaryKey(id);
    }

    @Override
    public List<T> findAll() {
        return basemapper.selectAll();
    }

    @Override
    @Transactional
    public void saveOrUpdate(T t) {
        if (t.getId() == null){
            basemapper.insertSelective(t);
        }else{
            basemapper.updateByPrimaryKeySelective(t);
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        basemapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageList<T> findPage(Q q) {
        PageHelper.startPage(q.getPage(),q.getSize());
        List<T> list = basemapper.selectAll();
        //如果一条数据都没有，直接返回默认的total = 0 list是new ArrayList
        if (list.size() == 0){
            return new PageList<>();
        }
        PageInfo<T> pageInfo = new PageInfo<>(list);
        return new PageList<>(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public void batchDelete(Long[] ids) {
        if (ids.length == 0){
            return;
        }
        for (Long id : ids) {
            //删除
            basemapper.deleteByPrimaryKey(id);
        }

    }
}
